package com.jinsp.network;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jinsp.networklibrary.IConnectCallback;
import com.jinsp.networklibrary.IConnectServer;
import com.jinsp.networklibrary.TCPConnectConfig;
import com.jinsp.networklibrary.TCPConnectService;
import com.jinsp.networklibrary.TCPSessionManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private TextView tv_receiver;
    private IConnectServer connectServer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_receiver = findViewById(R.id.tv_receiver);
        Intent intent = new Intent(this, TCPConnectService.class);
        TCPConnectConfig tcpConnectConfig = new TCPConnectConfig.Builder()
                .setServiceIP("192.168.0.132")
                .setServicePort(5577)
                .setCipher("vefx21evuym2cｸ")
                .setCodeFormat("utf-8")
                .setConnectTimeOut(3)
                .setUseJsonData(true)
                .setSendDataForJsonString(true)
                .setReadIdleTime(10)
                .setClientStateData(0)
                .build();
        intent.putExtra(TCPConnectService.CONNECT_CONFIG, tcpConnectConfig);
        startService(intent);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    private final ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            connectServer = IConnectServer.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private final IConnectCallback.Stub connectCallback = new IConnectCallback.Stub() {
        @Override
        public void connectSuccess() throws RemoteException {
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show());
        }

        @Override
        public void connectFailed(int errorCode) throws RemoteException {
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "连接失败 " + errorCode, Toast.LENGTH_SHORT).show());
        }
    };

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_connect) {
            if (connectServer != null) {
                try {
                    connectServer.connectServer(connectCallback);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } else if (id == R.id.btn_disconnect) {
            if (connectServer != null) {
                try {
                    connectServer.disconnect();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } else if (id == R.id.btn_send) {
            new Thread(() -> {
                TestCommand testCommand = new TestCommand();
                List<Test> list = new ArrayList<>();
                for (int i = 0; i < 2; i++) {
                    Test test = new Test();
                    test.setCreateTime("2022-01-18-11-04-23");
                    test.setDeviceID("RS1000DI");
                    test.setLogType(1);
                    test.setUID(UUID.randomUUID().toString());
                    test.setUser("client");
                    test.setLogText("测试数据：" + i);
                    list.add(test);
                }
                testCommand.setCommandData(list);
                TCPSessionManager.getInstance().sendCommand(testCommand);
            }).start();
        }
    }

    @Subscribe
    public void onTCPReceiverData(String data) {
        if (!TextUtils.isEmpty(data)) {
            tv_receiver.setText(data);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        stopService(new Intent(this, TCPConnectService.class));
    }
}